package config;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import struts.form.XmlBean;

public class Struts_config {
	public Struts_config(){
		
	}
	
	public static Map<String,XmlBean> struts_xml(String xmlPath )throws Exception{
		SAXBuilder builder = new SAXBuilder();
//		Document document = builder.build(new File("WebRoot/WEB-INF/struts-config.xml"));
		Document document = builder.build(new File(xmlPath));
		Element root = document.getRootElement();
		Map<String,XmlBean> rmap = new HashMap<String, XmlBean>();//因为XmlBean有可能是多个，多个路径处理多个类
//		Element actionform = root.getChild("formbeans");
//		List<Element> form = actionform.getChildren();
//		 for(Element e:form){
//			 String name = e.getAttributeValue("name");
//			 String clas= e.getAttributeValue("class");
//			// System.out.println("formbeans:name="+name+"||class="+clas);
//		 } 
//	
		 Element actionroot = root.getChild("action-mapping");
		 List<Element> actio = actionroot.getChildren();
		 String path = "";
		 for(Element e:actio){
			  XmlBean action = new XmlBean();
			  String name = e.getAttributeValue("name");//name值是相同的,此时获取的是action中的name
			  action.setBeanName(name);
			  Element actionform = root.getChild("formbeans");
			  List<Element> form = actionform.getChildren();
			  for(Element ex : form){
				  if(name.equals(ex.getAttributeValue("name"))){
					  String formclass = ex.getAttributeValue("class");
					  action.setFormClass(formclass);//要操作的对象
					  break;
				  }
				  
			  }
			 path = e.getAttributeValue("path");
			 action.setPath(path);
			 String type = e.getAttributeValue("type");
			 action.setActionType(type);
			 List<Element> forward = e.getChildren();
			 Map<String,String> map = new HashMap<String, String>(); 
			 for(Element x : forward){
				 String fname = x.getAttributeValue("name");
				 String fvalue = x.getAttributeValue("value");
				 map.put(fname, fvalue);
				
			 }
			 action.setActionForward(map);
              rmap.put(path, action);
		 }	
		 return rmap;
	}
	
//    public static void main(String[] args) throws Exception {
//		Map<String,XmlBean> m = new Struts_config().struts_xml();
//		for(Map.Entry<String, XmlBean> entry:m.entrySet()){
//			System.out.println(entry.getKey()+":"+entry.getValue().getBeanName());
//		}
//	}
	 
	

}
